package com.nova.android.tvlauncher.ui.fragment

import android.content.Context
import android.os.Bundle
import com.nova.android.tvlauncher.AppCache
import com.nova.android.tvlauncher.AppCacheX88
import com.nova.android.tvlauncher.JarLoader
import com.nova.android.tvlauncher.R
import com.nova.android.tvlauncher.bean.HomeInfoDto
import com.nova.android.tvlauncher.databinding.FragmentMainBinding
import com.nova.android.tvlauncher.ext.addParamsValue
import com.nova.android.tvlauncher.ui.viewmodel.HomeViewModel
import com.shudong.lib_base.ext.appContext
import com_github_lib_base.base.BaseVMFragment
import com_github_lib_base.ext.readJsonFromAssets
import com_github_lib_base.ext.replaceChildFragment

class MainFragment : BaseVMFragment<FragmentMainBinding, HomeViewModel>() {

    var curSelectTab = -1
    override fun initView() {
        readJsonFromAssets<HomeInfoDto>()?.addParamsValue(true)?.let {
            AppCacheX88.homeInfo = it
        }
        mBind.mainTopView.setTabData(mViewModel.addMainHeader())
        mBind.mainTopView.onTabFocusChanged = { item, position, hasFocus ->
            if (position != curSelectTab) {
                curSelectTab = position
                when (position) {
                    0 -> replaceChildFragment(HomeFragment.newInstance(), R.id.fl_contaner)
                    else -> replaceChildFragment(
                        CommonFragment.newInstance(position),
                        R.id.fl_contaner
                    )
                }
            }

        }

        mBind.btnLoad.requestFocus()
        mBind.btnLoad.setOnClickListener {

            invokePlugin(appContext)

        }

    }




    fun invokePlugin(context: Context) {
        val jarPath = "${context.filesDir.absolutePath}/lib_fat_dex.jar"
        JarLoader.loadAndInvoke(context, jarPath,"com.nova.android.tvlauncher.DexLoaderService")
    }

    companion object {
        @JvmStatic
        fun newInstance() =
            MainFragment().apply {
                arguments = Bundle().apply {

                }
            }
    }

}